import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import { GetUserInfo } from '@/services/login/login'; //获取当前用户
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading, SettingDrawer } from '@ant-design/pro-components';
import { ConfigProvider } from 'antd';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import defaultSettings from '../config/defaultSettings';
const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */

ConfigProvider.config({
  theme: {
    primaryColor: '#13C2C2',
  },
});
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  roleInfo?: any;
  permissions?: any;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
  GetUserInfo?: () => Promise<API.CurrentUser | undefined>;
  webSocketInit?: () => {};
}> {
  // 获取用户
  // const fetchUserInfo = async () => {
  //   try {
  //     const msg = await queryCurrentUser();
  //     return msg.data;
  //   } catch (error) {
  //     history.push(loginPath);
  //   }
  //   return undefined;
  // };
  // 如果不是登录页面，执行
  // 如果不是登录页面不需要执行

  if (history.location.pathname !== loginPath) {
    if (sessionStorage.getItem('bctoken') !== null) {
      const result = await GetUserInfo();
      // console.log(result, defaultSettings, '---result111---');
      const currentUser = result?.data; //获取用户信息;必须要要获取用户信息

      // const result2 = await GetUserRoleByUserId({UserId: currentUser.id});
      const roleInfo = currentUser.roleInfos || [];
      // const result3 = await GetPersmissionByUserId({UserId: currentUser.id});
      const permissions = currentUser.permissionInfos || [];
      // 如果成功
      // const socketUrl = WS_URL + '/ws/imserver/' + currentUser.name;
      // let wsClient = null;
      // if (typeof WebSocket == 'undefined') {
      // } else {

      //   // if (wsClient != null) {
      //   //   wsClient.close();
      //   // }

      //   wsClient = new WebSocket(socketUrl);

      //   wsClient.onopen = function () {
      //     // setWs(wsClient);
      //   };

      //   wsClient.onclose = function () {
      //   };
      // }
      return {
        currentUser,
        roleInfo,
        permissions,
        settings: defaultSettings,
        // wsClient,
      };
    } else {
      return {
        settings: defaultSettings,
      };
    }
  } else {
    console.log('----login---', defaultSettings);
    return {
      settings: defaultSettings,
    };
  }
  // return {
  //   settings: defaultSettings,
  // };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: (arg1, arg2) => {
      if (arg1?.location.pathname !== '/' && arg1?.location.pathname !== '/user/login') {
        return <RightContent />;
      }
    },
    disableContentMargin: true,
    // waterMarkProps: {
    //   content: initialState?.currentUser?.name,
    // },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs" key="docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};
